import { Component, Host, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

import { HttpClient } from '@angular/common/http';
import { CompanyEsgService } from '../companyEsg.service';
import { AppComponent } from '../../../../../app.component';
import { Subscription } from 'rxjs';
import { CompanyService } from '../../company.service';
import { EsgOverallPerformanceSummary } from './models/EsgOverallPerformanceSummary.model';
import { EsgRelativePosition } from './models/EsgRelativePosition.model';
import { EsgHistoricalPerformanceSummary, HistoricalPerformance } from './models/esgHistoricalPerformanceSummary.model';
import { UtilsService } from '../../../../../shared/services/utils.service';
import { LinearChartData } from '../../../../../shared/directives/charts/models/linearChart.model';
import { ControversyQualitativePerformanceModel } from '../../../../../shared/models/qualitativePerformance.model';
import { ResearchState } from '../../../research.service';
import { ClusterModelWrapper } from '../../../riskCluster/cluster.model';
import { AnalyticsService } from '../../../../../shared/services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../../../../shared/models/googleAnalytics.model';

/**
 * Company ESG summary component
 *
 * Author: Sorin Spiru, Andrei Istrate
 * Date: 23.02.2018
 */
@Component({
  selector: 'esg-summary',
  templateUrl: './esgSummary.component.html',
  styleUrls: [
    '../../company.component.scss',
    './esgSummary.component.scss'
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CompanyESGSummaryComponent {
  private sub: Subscription;
  public esgOverallPerformanceSummary: EsgOverallPerformanceSummary;
  public esgRelativePosition: EsgRelativePosition;
  public esgHistoricalPerformanceSummary: EsgHistoricalPerformanceSummary;
  public overallChartData: LinearChartData[];
  public indicators: ControversyQualitativePerformanceModel[];
  public companyId;
  public formatIssueWeight: Function = UtilsService.formatIssueWeight;
  public researchType;
  public currentClusters;

  constructor(
    @Host() private rootComponent: AppComponent,
    private cdRef: ChangeDetectorRef,
    private companyService: CompanyService,
    private companyEsgService: CompanyEsgService,
    private http: HttpClient,
    private analyticsService: AnalyticsService) { }

  ngOnInit() {
    this.sub = this.companyService.company.subscribe(data => {
      this.researchType = data.comprehensiveEsgResearchState === ResearchState.ResearchAvailable ? 'comprehensive' : 'core';
      this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('OnscreenESGRatingReport', 'Research', { CompanyId: data.id }));
      this.companyId = data.companyNameUrlFriendly;
      this.companyEsgService.getEsgOverallPerformanceSummary(data.id).subscribe(data => {
        this.esgOverallPerformanceSummary = data;
        this.cdRef.markForCheck();
        this.rootComponent.finishLoading();
      });

      this.companyEsgService.getEsgRelativePosition(data.id).subscribe(data => {
        this.esgRelativePosition = data;
        this.cdRef.markForCheck();
      });

      this.companyEsgService.getEsgHistoricalPerformanceSummary(data.id).subscribe(data => {
        this.esgHistoricalPerformanceSummary = data;
        this.overallChartData = this.getDataForChart(this.esgHistoricalPerformanceSummary.overall);
        this.cdRef.markForCheck();
      });

      this.companyEsgService.getControversyQualitativePerformance(data.id).subscribe(data => {
        this.indicators = data;
        this.cdRef.markForCheck();
      });

      this.companyEsgService.getEsgThresholds(data.peerGroup).subscribe(thresholds => {
        this.currentClusters = thresholds.map((threshold, index) => {
          return new ClusterModelWrapper(5 - index, (5 - index).toString(), undefined, undefined, null, threshold.upper, false);
        });
        this.cdRef.markForCheck();
      });
    });
  }

  public getPercentileOrdinal(): string {
    return UtilsService.getOrdinalNameEnd(this.esgOverallPerformanceSummary.percentile.comparativeGroupPercentileRank);
  }

  private getDataForChart(historicalPerformance: HistoricalPerformance): LinearChartData[] {
    return historicalPerformance.companyHistory.map((companyHistory, index) => {
      return {
        scoreCompany: companyHistory.score,
        date: companyHistory.date,
        scoreIndustryLead: historicalPerformance.industryLeaderHistory[index].score,
        scoreGrouptAvg: historicalPerformance.peerGroupAvgHistory[index].score
      };
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}
